package cn.xiaoyangh.org.service.impl;

import cn.xiaoyangh.basic.service.impl.BaseServiceImpl;
import cn.xiaoyangh.org.domain.Department;
import cn.xiaoyangh.org.domain.Employee;
import cn.xiaoyangh.org.mapper.DepartmentMapper;
import cn.xiaoyangh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService{

    @Autowired
    private DepartmentMapper dm;

    @Override
    @Transactional
    public void save(Department dep) {
/*        Employee manager = dep.getManager();
        System.out.println(dep);
        if(manager!=null){
            Long id = manager.getId();
            dep.setManager_id(id);
        }
        Department parent = dep.getParent();
        if(parent!=null){
            Long pid = parent.getId();
            dep.setParent_id(pid);
        }*/
        //先添加否则没有id,通过添加的sql拿到id
        dm.save(dep);
        //判断返回的对象是否有上级
        update(dep);
    }

    @Override
    @Transactional
    public void update(Department dep) {
/*        Employee manager = dep.getManager();
        if(manager!=null){
            Long id = manager.getId();
            dep.setManager_id(id);
        }
        Department parent = dep.getParent();
        if(parent!=null){
            Long pid = parent.getId();
            dep.setParent_id(pid);
        }*/

        if(dep.getParent().getId()==null){
            dep.setDirPath("/"+dep.getId());
        }else {
            if (dep.getParent().getId()!=null){
                Department dept = dm.loadById(dep.getParent().getId());
                dep.setDirPath(dept.getDirPath()+"/"+dep.getId());
            }else{
                dep.setDirPath("/"+dep.getId());
            }

        }
        dm.update(dep);
    }


    @Override
    public List<Department> deptTree() {
        return dm.deptTree();
    }
}
